<template>
  <div ref="chartRef" style="width: 100%;height:100%"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, watch, defineProps } from 'vue';

// 传递过来的月份数据
const props = defineProps({
  monthData: {
    type: Array,
    // default: () => [],
    required: true
  }
})

const chartRef = ref(null);
let myChart;

onMounted(() => {
  if (!chartRef.value) return;
  myChart = echarts.init(chartRef.value);
  updateChart();
});

const updateChart = () => {
  const option = {
    title: {
      text: '园区上半年收支分析图'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    toolbox: {
      feature: {
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },
    legend: {
      data: ['收入', '支出']
    },
    xAxis: [
      {
        type: 'category',
        data: props.monthData.map(item => item.month),
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '收入支出 / 万元',
        min: 0,
        max: 2000,
        interval: 500,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '            利润',
        min: 0,
        max: 1000,
        axisLabel: {
          formatter: "{value} "
        }
      }
    ],
    series: [
      {
        name: '支出',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        data: props.monthData.map(item => item.month_expend)
      },
      {
        name: '收入',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        data: props.monthData.map(item => item.month_income)
      },
      {
        name: '盈余',
        type: 'line',
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        data: props.monthData.map(item => item.month_balance)
      }
    ]
  };
  myChart.setOption(option);
};

watch(() => props.monthData, (newData) => {
  if (myChart) {
    updateChart();
  }
}, { immediate: true });
</script>